//
//  UTSimulateRefreshViewController.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/10.
//

import UIKit

class UTSimulateRefreshViewController: UTBaseViewController {
    
    var handler:((UTSimulateModel) -> Void)?
    var model: UTSimulateModel?
    
    @IBOutlet weak var durationSlider: UISlider!
    @IBOutlet weak var durationLabel: UILabel!
    @IBOutlet weak var durationCenterX: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(white: 0, alpha: 0.3)
        durationSlider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
        if let model = model {
            durationSlider.value = Float(model.refreshFrequency)
            durationLabel.text = "\(model.refreshFrequency)秒"
            durationCenterX.constant = durationSlider.frame.origin.x + CGFloat(durationSlider.value / durationSlider.maximumValue) * durationSlider.frame.width - durationSlider.frame.origin.x - durationSlider.frame.width / 2 + 5
        }
    }
    
    
    @IBAction func didClose(_ sender: Any) {
        dismiss(animated: false)
    }
    
    @objc func sliderValueChanged(_ sender: UISlider) {
        updateValueLabelPosition(sender)
    }
    
    func updateValueLabelPosition(_ sender: UISlider) {
        let value = Int(sender.value)
        if sender == durationSlider {
            guard let model = model else { return }
            model.refreshFrequency = value
            let centerX = durationSlider.frame.origin.x + CGFloat(durationSlider.value / durationSlider.maximumValue) * durationSlider.frame.width
            durationLabel.text = "\(value)秒"
            durationCenterX.constant = centerX - durationSlider.frame.origin.x - durationSlider.frame.width / 2 + 5
        }
    }
    
    @IBAction func save(_ sender: UIButton) {
        if let handler = handler {
            guard let model = model else { return }
            handler(model)
        }
        dismiss(animated: false)
    }
    
}
